/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.user.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.MessageNamespaces;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.service.CommentService;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.common.service.MessageService;
import etcore.webapp.grouptalk.user.object.Focus;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.user.service.FocusService;
import etcore.webapp.grouptalk.user.service.UserService;
import etcore.webapp.grouptalk.util.DateUtil;

/**
 * This action validates the request and set the corresponding attributes
 * required by viewUser page.
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class ViewUserAction extends AbstractAction {

	private static final long serialVersionUID = -5098567988800138916L;
	// validate result
	public static final int ACCESS_ALLOWED = 0;
	public static final int ERROR = 1;
	public static final int VIEW_ALLOWED = 2;
	public static final String START_PID = "startpid";
	public static final String END_PID = "endpid";
	public static final String COMMENT_NUM = "commentNum";
	public static final String LAST_COMMENT = "lastComment";
	public static final String ADD_FOCUS = "addFocus";
	public static final String COMMUNITIES_MSG_SIZE = "communitiesMsgSize";
	public static final String BOOKMARKS_MSG_SIZE = "bookmarksMsgSize";
	public static final String REMINDERS_MSG_SIZE = "remindersMsgSize";
	public static final String INFO_MSG_SIZE = "infoMsgSize";

	// parameter/attributes constants

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {
		boolean included = true;
		HttpSession session = request.getSession(true);
		User user = (User) session.getAttribute(Messages.SESSION_USER);

		String userName = request.getParameter(PageConstants.TARGET_USERNAME);
		if (userName != null) {
			try {
				userName = new String(
						userName.getBytes(PageConstants.ENCODING_ISO88591),
						(PageConstants.ENCODING_UTF8));
			} catch (Exception e) {
				e.printStackTrace();
			}
			UserService userService = new UserService();
			User result = userService.findByUserName(userName);
			// System.out.println(result.getUserName());
			if (result != null) {
				request.setAttribute(PageConstants.TARGET_USER, result);
				FocusService focusService = new FocusService();
				if (user != null
						&& !focusService.isAdded(user.getUserName(), userName)
						&& !user.getUserName().equals(userName))
					included = false;
				request.setAttribute("included", included);
				return VIEW_ALLOWED;
			}

			request.setAttribute("included", included);
			return ACCESS_ALLOWED;
		}

		return ACCESS_ALLOWED;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (ERROR == validationResult) {
			request.setAttribute("init", "login");
			return "/";
		}
		return PageConstants.PAGE_PATH_VIEWUSER;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		if (VIEW_ALLOWED == validationResult) {
			
			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute(PageConstants.SESSIONUSER);
			String cmd = request.getParameter(PageConstants.CMD);
			FocusService focusService = new FocusService();
			User targetUser = (User) request
					.getAttribute(PageConstants.TARGET_USER);
			if (ADD_FOCUS.equals(cmd)
					&& !focusService.isAdded(user.getUserName(),
							targetUser.getUserName())
					&& !user.getUserName().equals(targetUser.getUserName())) {

				Focus focus = new Focus();
				focus.setFromUser(user.getUserName());
				focus.setToUser(targetUser.getUserName());
				focus.setAddTime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
				focusService.save(focus);
				String msg = null;
				String lang = (String) session.getAttribute("lang");
				if (lang != null && lang.equals(Messages.LANG_EN)) {
					msg = Messages.getELabel(Messages.MSG_SUCCESS);
				} else {
					msg = Messages.getLabel(Messages.MSG_SUCCESS);
				}
				request.setAttribute(Messages.MSG, msg);
				request.setAttribute("included", true);
			}
			getUserProfile(request);
		}
		// TODO Auto-generated method stub

	}

	private void getUserProfile(HttpServletRequest request) {

		User user = (User) request.getAttribute("targetUser");

		if (user == null)
			return;

		//boolean isAdmin = (Boolean) request.getAttribute(PageConstants.ISADMIN);
		long userFollowingCount = 0, userFollowersCount = 0, userGroupsCount = 0, userFavouriteCount = 0, userMessagesCount = 0, userCommentsCount = 0;
		FocusService focusService = new FocusService();
		MessageService msgService = new MessageService();
		GroupService groupService = new GroupService();
		CommentService commentService = new CommentService();
		userFollowingCount = focusService.findSizeByProperty("fromUser",
				user.getUserName());
		userFollowersCount = focusService.findSizeByProperty("toUser",
				user.getUserName());
		userGroupsCount = groupService.findFavouriteGroupsSize(
				user.getUserName(), 2);
		userFavouriteCount = msgService.findSizeOfFavouriteMessages(user
				.getUserName());
 
	userMessagesCount = msgService.findSizeOfPublicMessages(
					PageConstants.USERNAME, user.getUserName());
		userCommentsCount = commentService.findPublicCommentsSizeByProperty(
				PageConstants.USERNAME, user.getUserName());
		request.setAttribute("userFollowingCount", userFollowingCount);
		request.setAttribute("userFollowersCount", userFollowersCount);
		request.setAttribute("userGroupsCount", userGroupsCount);
		request.setAttribute("userFavouriteCount", userFavouriteCount);
		request.setAttribute("userMessagesCount", userMessagesCount);
		request.setAttribute("userCommentsCount", userCommentsCount);
	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#
	 * buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<String> namespaces = new ArrayList<String>();
		namespaces.add(MessageNamespaces.USER_PROFILE);
		return namespaces;
	}

}
